package net.siren93.smh.dao.impl;

import net.siren93.smh.dao.EmployeeDao;
import net.siren93.smh.entity.EmployeeEntity;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by siren93 on 15/9/25.
 */
@Repository("employeeDao")
public class EmployeeDaoImpl implements EmployeeDao {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public EmployeeEntity load(Integer id) {
        return (EmployeeEntity)getCurrentSession().load(EmployeeEntity.class, id);
    }

    public EmployeeEntity get(Integer id) {
        return (EmployeeEntity)getCurrentSession().get(EmployeeEntity.class, id);
    }

    @SuppressWarnings("unchecked")
    public List<EmployeeEntity> findAll() {
        List<EmployeeEntity> list = getCurrentSession().createQuery("from EmployeeEntity ").list();
        return list;
    }

    public EmployeeEntity findByName(String name) {
        String hql = "from EmployeeEntity as entity where entity.name=:name";
        Query query = getCurrentSession().createQuery(hql);
        query.setString("name", name);
        List<EmployeeEntity> list = query.list();
        if(list != null && list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    public void persist(EmployeeEntity entity) {
        getCurrentSession().persist(entity);
    }

    public Integer save(EmployeeEntity entity) {
        return (Integer)getCurrentSession().save(entity);
    }

    public void saveOrUpdate(EmployeeEntity entity) {
        getCurrentSession().saveOrUpdate(entity);
    }

    public void delete(Integer id) {
        EmployeeEntity employee = load(id);
        getCurrentSession().delete(employee);
    }

    public void flush() {
        getCurrentSession().flush();
    }

    @Override
    public List<EmployeeEntity> findByPage(int page, int rows) {
        String hql = "from EmployeeEntity";
        Query query = getCurrentSession().createQuery(hql);
        query.setFirstResult((page - 1) * rows);
        query.setMaxResults(rows);
        return query.list();
    }
}
